package org.testis.communication.client;

import java.io.IOException;
import org.snmp4j.CommunityTarget;
import org.snmp4j.PDU;
import org.snmp4j.Snmp;
import org.snmp4j.TransportMapping;
import org.snmp4j.event.ResponseEvent;
import org.snmp4j.mp.MPv3;
import org.snmp4j.security.SecurityModels;
import org.snmp4j.security.SecurityProtocols;
import org.snmp4j.security.USM;
import org.snmp4j.smi.Address;
import org.snmp4j.smi.GenericAddress;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.VariableBinding;
import org.snmp4j.transport.DefaultUdpTransportMapping;


/**
 * A class to define snmp requests
 * @author nurhat
 */
public class AtofSnmpClient
{

    /**
     * Checks availablity of snmp for the given host
     * @param host
     * @param port
     * @return true if snmp is available
     * @throws java.lang.Exception
     */
    public boolean checkValidation(String host,String oid,
                                   int port)
    {
        try {
            Address targetAddress =
                GenericAddress.parse("udp:" + host + "/" + port);
            TransportMapping transport =
                new DefaultUdpTransportMapping();
            Snmp snmp = new Snmp(transport);
            USM usm =
                new USM(SecurityProtocols.getInstance(),
                        new OctetString(MPv3.createLocalEngineID()),
                        0);
            SecurityModels.getInstance().addSecurityModel(usm);
            transport.listen();

            CommunityTarget target = new CommunityTarget();
            target.setCommunity(new OctetString("public"));
            target.setAddress(targetAddress);
            target.setRetries(1);
            target.setTimeout(1500);

            PDU pdu = new PDU();
            pdu.add(new VariableBinding(new OID(oid)));
            pdu.setType(PDU.GET);

            ResponseEvent response = snmp.send(pdu,
                                               target);

            PDU responsePDU = response.getResponse();
            if (responsePDU == null) {
                return false;
            }
            else {
                return true;
            }
        } catch (IOException ex) {
        }
        return false;

    }
}
